package com.sun.evening.manager.service.impl;

import com.sun.evening.core.constant.AESConstant;
import com.sun.evening.core.constant.MinioConstant;
import com.sun.evening.dao.entity.PictureList;
import com.sun.evening.dao.entity.UserControls;
import com.sun.evening.dao.mapper.PictureListMapper;
import com.sun.evening.dao.vo.PictureListVo;
import com.sun.evening.manager.aes.MyAESUtil;
import com.sun.evening.manager.minio.MinioUtils;
import com.sun.evening.manager.redis.RedisUtils;
import com.sun.evening.manager.service.PictureServer;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Objects;

@Service
public class PictureServerImpl implements PictureServer {
    @Resource
    private MinioUtils minioUtils;
    @Resource
    private PictureListMapper pictureListMapper;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private MyAESUtil myAESUtil;
    @Override
    @Transactional(rollbackFor = Exception.class)
    @ApiModelProperty("根据图片名称验证查询返回图片临时下载链接")
    public PictureListVo getPictureUrl(String pictureName) {
        PictureList pictureList=pictureListMapper.selectPictureListByName(pictureName);
        if (Objects.isNull(pictureList)){
            return null;
        }
        String url = minioUtils.getPresignedObjectUrl(MinioConstant.BUCKET_NAME,pictureList.getPictureName(), 180);
        PictureListVo pictureListVo=new PictureListVo();
        pictureListVo.setPictureId(pictureList.getPictureId());
        pictureListVo.setPictureUrl(url);
        pictureListVo.setPictureName(pictureList.getPictureName());
        pictureListVo.setPictureTips(pictureList.getPictureTips());
        return pictureListVo;
    }

    @Override
    public Integer insertRedisControls(PictureListVo pictureListVo, String openId) throws Exception{
        String dbOpenId=myAESUtil.Encrypt(openId, AESConstant.AES_KEY_DB);
        UserControls userControls=new UserControls();
        Timestamp now = new Timestamp(System.currentTimeMillis());
        userControls.setPictureId(pictureListVo.getPictureId());
        userControls.setUserOpenId(openId);
        userControls.setControlsTypeId(1);
        userControls.setCreateTime(now);
        return 0;
    }
}
